package com.ctsi.auth.vcc.manager.impl;

import com.ctsi.auth.vcc.manager.UserAccountLockService;
import com.ctsi.auth.vcc.manager.UserAccoutLockCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author zhangjw
 * @className UserAccountLockServiceImpl
 * @description TODO
 * @date 2019/2/27 13:56
 **/
@Component
public class UserAccountLockServiceImpl implements UserAccountLockService {

    @Autowired
    private UserAccoutLockCache userAccoutLockCache;

    /**
     * 允许尝试登陆次数
     */
    @Value("${security.oauth.user-login.try-count:5}")
    private int testCount;

    @Value("${security.oauth.user-login.lock-time:300}")
    private int lockTime;

    /**
     * 判断用户是否被临时锁定
     *
     * @param userName
     * @return
     */
    @Override
    public boolean isLock(String userName) {
        userAccoutLockCache.initCache(USERACCOUNT_LOCK_CACHE_NAME,userName,testCount);
        return userAccoutLockCache.get(USERACCOUNT_LOCK_CACHE_NAME,userName) == 0;
    }

    /**
     * 剩余的登陆次数
     *
     * @param userName
     * @return
     */
    @Override
    public int minus(String userName) {
        userAccoutLockCache.initCache(USERACCOUNT_LOCK_CACHE_NAME,userName,testCount);
        return userAccoutLockCache.getAndIncrement(USERACCOUNT_LOCK_CACHE_NAME,userName,lockTime);
    }

    /**
     * 删除用户临时锁
     *
     * @param userName
     */
    @Override
    public void removeLock(String userName) {
        userAccoutLockCache.remove(USERACCOUNT_LOCK_CACHE_NAME,userName);
    }
}
